package com.yxplearn.mybatisplus.match;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Queue;
import java.util.concurrent.*;

@Component
public class MatchQueueService implements ApplicationContextAware {

    private static ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    private static Runnable matchRunnable = () -> {
        MatchResult matchResult = new MatchResult();
        matchResult.setState(0);
        Queue<Player> matchQueue = MatchQueueManager.getMatchQueue();
        if (!matchQueue.isEmpty()) {
            matchResult.setState(1);
        }
        if (matchQueue.size() >= 8) {
            Queue<Player> playerList = new LinkedBlockingQueue<>();
            for (int i = 0; i < 8; i++) {
                Player poll = matchQueue.poll();
                if (poll != null) {
                    playerList.add(poll);
                }
            }
            matchResult.setMatchPlays(playerList);
            matchResult.setState(2);
        }
        matchResult.setMatchSize(matchQueue.size());
        if (matchResult.getState() == 2) {
            matchResult.setMatchSize(8);
        }
        if (matchResult != null && matchResult.getState() != 0) {
            MatchQueueManager.getMatchResults().add(matchResult);
        }
    };

    private static Runnable sendMatchResult = () -> {
        MatchResult firstMatchResults = MatchQueueManager.getFirstMatchResults();
        if (firstMatchResults != null) {
            System.out.println(firstMatchResults.toString());
        }
    };

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        scheduledExecutorService.scheduleAtFixedRate(matchRunnable, 1, 1, TimeUnit.SECONDS);

        scheduledExecutorService.scheduleAtFixedRate(sendMatchResult, 1, 1, TimeUnit.SECONDS);
    }
}
